<template>
  <view class="feedback-management">
    <!-- 页面头部 -->
    <view class="page-header">
      <uni-stat-breadcrumb class="breadcrumb" />
      <view class="header-content">
        <view class="page-title">
          <uni-icons type="chatboxes" size="24" color="#ffffff"></uni-icons>
          <text class="title-text">用户反馈管理</text>
        </view>
        <view class="header-stats">
          <view class="stat-item">
            <text class="stat-number">{{ statistics.total }}</text>
            <text class="stat-label">总反馈数</text>
          </view>
          <view class="stat-item">
            <text class="stat-number">{{ statistics.pending }}</text>
            <text class="stat-label">待处理</text>
          </view>
          <view class="stat-item">
            <text class="stat-number">{{ statistics.resolved }}</text>
            <text class="stat-label">已解决</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 搜索和筛选区域 -->
    <view class="search-section">
      <uni-card>
        <view class="search-form">
          <uni-easyinput 
            v-model="searchKeyword" 
            placeholder="搜索用户姓名、联系方式或反馈内容" 
            prefixIcon="search"
            clearable
            @confirm="handleSearch"
            @clear="handleSearch">
          </uni-easyinput>
          
          <uni-data-select 
            v-model="filterType" 
            :localdata="typeOptions" 
            placeholder="反馈类型"
            @change="handleSearch">
          </uni-data-select>
          
          <uni-data-select 
            v-model="filterStatus" 
            :localdata="statusOptions" 
            placeholder="处理状态"
            @change="handleSearch">
          </uni-data-select>
          
          <button class="search-btn" @click="handleSearch">
            <uni-icons type="search" size="16"></uni-icons>
            搜索
          </button>
          
          <button class="reset-btn" @click="resetSearch">
            <uni-icons type="refresh" size="16"></uni-icons>
            重置
          </button>
        </view>
      </uni-card>
    </view>

    <!-- 数据表格 -->
    <view class="table-section">
      <uni-card>
        <unicloud-db 
          ref="udb" 
          collection="feedback" 
          field="name,contact,type,description,images,createTime,status,adminReply,replyTime" 
          :where="where" 
          page-data="replace"
          :orderby="orderby" 
          :getcount="true" 
          :page-size="pageSize" 
          :page-current="pageCurrent"
          v-slot:default="{data,pagination,loading,error}" 
          loadtime="manual" 
          @load="onDataLoad">
          
          <uni-table 
            :loading="loading" 
            :emptyText="error.message || '暂无反馈数据'" 
            border 
            stripe>
            
            <uni-tr>
              <uni-th align="center" width="80">序号</uni-th>
              <uni-th align="center" width="100">用户姓名</uni-th>
              <uni-th align="center" width="120">联系方式</uni-th>
              <uni-th align="center" width="100">反馈类型</uni-th>
              <uni-th align="center" width="200">反馈内容</uni-th>
              <uni-th align="center" width="100">处理状态</uni-th>
              <uni-th align="center" width="140">提交时间</uni-th>
              <uni-th align="center" width="160">操作</uni-th>
            </uni-tr>
            
            <uni-tr v-for="(item,index) in data" :key="index">
              <uni-td align="center">{{ (pageCurrent - 1) * pageSize + index + 1 }}</uni-td>
              <uni-td align="center">
                <view class="user-info">
                  <uni-icons type="person" size="16" color="#909399"></uni-icons>
                  <text>{{ item.name }}</text>
                </view>
              </uni-td>
              <uni-td align="center">
                <view class="contact-info">
                  <text>{{ item.contact }}</text>
                </view>
              </uni-td>
              <uni-td align="center">
                <uni-tag :type="getTypeColor(item.type)" :text="item.type" size="small"></uni-tag>
              </uni-td>
              <uni-td align="center">
                <view class="content-preview" @click="showDetail(item)">
                  <text>{{ getContentPreview(item.description) }}</text>
                  <uni-icons v-if="item.images && item.images.length" type="image" size="14" color="#409EFF"></uni-icons>
                </view>
              </uni-td>
              <uni-td align="center">
                <uni-tag :type="getStatusColor(item.status)" :text="getStatusText(item.status)" size="small"></uni-tag>
              </uni-td>
              <uni-td align="center">
                <text class="time-text">{{ formatDateTime(item.createTime) }}</text>
              </uni-td>
              <uni-td align="center">
                <view class="action-buttons">
                  <button class="action-btn view-btn" @click="showDetail(item)">
                    <uni-icons type="eye" size="14"></uni-icons>
                    查看
                  </button>
                  <button class="action-btn reply-btn" @click="openReplyDialog(item)" v-if="item.status === 'pending'">
                    <uni-icons type="chat" size="14"></uni-icons>
                    回复
                  </button>
                </view>
              </uni-td>
            </uni-tr>
          </uni-table>
          
          <view class="uni-pagination-box">
            <uni-pagination 
              show-icon 
              :page-size="pagination.size" 
              :current="pagination.current" 
              :total="pagination.count" 
              @change="onPageChanged" />
          </view>
        </unicloud-db>
      </uni-card>
    </view>

    <!-- 详情弹窗 -->
    <uni-popup ref="detailPopup" type="dialog">
      <uni-popup-dialog 
        mode="base" 
        title="反馈详情" 
        @close="closeDetail">
        <view class="detail-content" v-if="currentDetail">
          <view class="detail-section">
            <view class="detail-row">
              <text class="detail-label">用户信息</text>
            </view>
            <view class="detail-info-card">
              <view class="info-row">
                <uni-icons type="person" size="16" color="#409EFF"></uni-icons>
                <text>{{ currentDetail.name }}</text>
              </view>
              <view class="info-row">
                <uni-icons type="phone" size="16" color="#409EFF"></uni-icons>
                <text>{{ currentDetail.contact }}</text>
              </view>
              <view class="info-row">
                <uni-icons type="calendar" size="16" color="#409EFF"></uni-icons>
                <text>{{ formatDateTime(currentDetail.createTime) }}</text>
              </view>
            </view>
          </view>
          
          <view class="detail-section">
            <view class="detail-row">
              <text class="detail-label">反馈类型</text>
              <uni-tag :type="getTypeColor(currentDetail.type)" :text="currentDetail.type"></uni-tag>
            </view>
          </view>
          
          <view class="detail-section">
            <view class="detail-row">
              <text class="detail-label">反馈内容</text>
            </view>
            <view class="feedback-content">
              {{ currentDetail.description }}
            </view>
          </view>
          
          <view v-if="currentDetail.images && currentDetail.images.length" class="detail-section">
            <view class="detail-row">
              <text class="detail-label">相关图片</text>
            </view>
            <view class="images-grid">
              <image 
                v-for="(img, index) in currentDetail.images" 
                :key="index"
                :src="img" 
                class="detail-image"
                @click="previewImage(img, currentDetail.images)">
              </image>
            </view>
          </view>
          
          <view v-if="currentDetail.adminReply" class="detail-section">
            <view class="detail-row">
              <text class="detail-label">管理员回复</text>
            </view>
            <view class="admin-reply-content">
              <text>{{ currentDetail.adminReply }}</text>
              <text class="reply-time">{{ formatDateTime(currentDetail.replyTime) }}</text>
            </view>
          </view>
        </view>
      </uni-popup-dialog>
    </uni-popup>

    <!-- 回复弹窗 -->
    <uni-popup ref="replyPopup" type="dialog">
      <uni-popup-dialog 
        mode="input" 
        title="回复用户反馈" 
        placeholder="请输入回复内容..."
        v-model="replyContent"
        @confirm="submitReply"
        @close="closeReplyDialog">
      </uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script>
import AuthManager from '@/utils/auth.js'

export default {
  data() {
    return {
      // 基础配置
      pageSize: 10,
      pageCurrent: 1,
      orderby: 'createTime desc',
      where: '',
      
      // 搜索筛选
      searchKeyword: '',
      filterType: '',
      filterStatus: '',
      
      // 统计数据
      statistics: {
        total: 0,
        pending: 0,
        resolved: 0
      },
      
      // 弹窗数据
      currentDetail: null,
      currentReplyItem: null,
      replyContent: '',
      
      // 筛选选项
      typeOptions: [
        { value: '', text: '全部类型' },
        { value: '功能建议', text: '功能建议' },
        { value: '问题反馈', text: '问题反馈' },
        { value: '使用体验', text: '使用体验' },
        { value: '其他', text: '其他' }
      ],
      
      statusOptions: [
        { value: '', text: '全部状态' },
        { value: 'pending', text: '待处理' },
        { value: 'processing', text: '处理中' },
        { value: 'resolved', text: '已解决' },
        { value: 'closed', text: '已关闭' }
      ]
    }
  },
  
  async onLoad() {
    // 认证检查
    const isAuthed = await AuthManager.pageAuthGuard()
    if (!isAuthed) {
      return
    }
    
    this.loadData();
  },
  
  methods: {
    // 加载数据
    loadData() {
      this.$refs.udb.loadData();
    },
    
    // 数据加载完成
    onDataLoad(data) {
      // 计算统计数据
      this.statistics.total = data.length;
      this.statistics.pending = data.filter(item => item.status === 'pending').length;
      this.statistics.resolved = data.filter(item => item.status === 'resolved').length;
    },
    
    // 搜索处理
    handleSearch() {
      let whereConditions = [];
      
      // 关键词搜索
      if (this.searchKeyword.trim()) {
        const keyword = this.searchKeyword.trim();
        whereConditions.push(`name.indexOf("${keyword}") > -1 || contact.indexOf("${keyword}") > -1 || description.indexOf("${keyword}") > -1`);
      }
      
      // 类型筛选
      if (this.filterType) {
        whereConditions.push(`type == "${this.filterType}"`);
      }
      
      // 状态筛选
      if (this.filterStatus) {
        whereConditions.push(`status == "${this.filterStatus}"`);
      }
      
      this.where = whereConditions.length > 0 ? whereConditions.join(' && ') : '';
      this.pageCurrent = 1;
      this.loadData();
    },
    
    // 重置搜索
    resetSearch() {
      this.searchKeyword = '';
      this.filterType = '';
      this.filterStatus = '';
      this.where = '';
      this.pageCurrent = 1;
      this.loadData();
    },
    
    // 分页处理
    onPageChanged(e) {
      this.pageCurrent = e.current;
      this.loadData();
    },
    
    // 显示详情
    showDetail(item) {
      this.currentDetail = item;
      this.$refs.detailPopup.open();
    },
    
    // 关闭详情
    closeDetail() {
      this.currentDetail = null;
    },
    
    // 打开回复对话框
    openReplyDialog(item) {
      this.currentReplyItem = item;
      this.replyContent = '';
      this.$refs.replyPopup.open();
    },
    
    // 关闭回复对话框
    closeReplyDialog() {
      this.currentReplyItem = null;
      this.replyContent = '';
    },
    
    // 提交回复
    async submitReply(content) {
      if (!content.trim()) {
        uni.showToast({
          title: '请输入回复内容',
          icon: 'none'
        });
        return;
      }
      
      try {
        const result = await uniCloud.callFunction({
          name: 'replyFeedback',
          data: {
            feedbackId: this.currentReplyItem._id,
            adminReply: content.trim()
          }
        });
        
        if (result.result.success) {
          uni.showToast({
            title: '回复成功',
            icon: 'success'
          });
          this.closeReplyDialog();
          this.loadData();
        } else {
          uni.showToast({
            title: result.result.message || '回复失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('回复失败:', error);
        uni.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      }
    },
    
    // 预览图片
    previewImage(current, urls) {
      uni.previewImage({
        current: current,
        urls: urls
      });
    },
    
    // 获取内容预览
    getContentPreview(content) {
      return content && content.length > 30 ? content.slice(0, 30) + '...' : content;
    },
    
    // 获取类型颜色
    getTypeColor(type) {
      const colorMap = {
        '功能建议': 'primary',
        '问题反馈': 'error', 
        '使用体验': 'warning',
        '其他': 'default'
      };
      return colorMap[type] || 'default';
    },
    
    // 获取状态颜色
    getStatusColor(status) {
      const colorMap = {
        'pending': 'warning',
        'processing': 'primary',
        'resolved': 'success',
        'closed': 'default'
      };
      return colorMap[status] || 'default';
    },
    
    // 获取状态文本
    getStatusText(status) {
      const textMap = {
        'pending': '待处理',
        'processing': '处理中', 
        'resolved': '已解决',
        'closed': '已关闭'
      };
      return textMap[status] || status;
    },
    
    // 格式化日期时间
    formatDateTime(timestamp) {
      if (!timestamp) return '-';
      const date = new Date(timestamp);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    }
  }
}
</script>

<style scoped>
.feedback-management {
  padding: 20rpx;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20rpx;
}

.breadcrumb {
  margin-bottom: 20rpx;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12rpx;
  color: white;
}

.page-title {
  display: flex;
  align-items: center;
  gap: 15rpx;
}

.title-text {
  font-size: 36rpx;
  font-weight: bold;
}

.header-stats {
  display: flex;
  gap: 40rpx;
}

.stat-item {
  text-align: center;
}

.stat-number {
  display: block;
  font-size: 32rpx;
  font-weight: bold;
}

.stat-label {
  font-size: 24rpx;
  opacity: 0.9;
}

.search-section {
  margin-bottom: 20rpx;
}

.search-form {
  display: flex;
  gap: 20rpx;
  align-items: center;
  flex-wrap: wrap;
  padding: 20rpx;
}

.search-btn, .reset-btn {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 10rpx 20rpx;
  border: none;
  border-radius: 6rpx;
  font-size: 28rpx;
  cursor: pointer;
}

.search-btn {
  background: #409EFF;
  color: white;
}

.reset-btn {
  background: #f4f4f5;
  color: #606266;
}

.table-section {
  background: white;
  border-radius: 12rpx;
}

.user-info, .contact-info {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.content-preview {
  cursor: pointer;
  color: #409EFF;
  text-decoration: underline;
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.time-text {
  font-size: 24rpx;
  color: #606266;
}

.action-buttons {
  display: flex;
  gap: 10rpx;
  justify-content: center;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 4rpx;
  padding: 8rpx 12rpx;
  border: none;
  border-radius: 4rpx;
  font-size: 24rpx;
  cursor: pointer;
}

.view-btn {
  background: #e1f3d8;
  color: #67c23a;
}

.reply-btn {
  background: #ecf5ff;
  color: #409eff;
}

.uni-pagination-box {
  padding: 20rpx;
  text-align: center;
}

.detail-content {
  padding: 20rpx;
  max-height: 80vh;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 30rpx;
}

.detail-row {
  display: flex;
  margin-bottom: 15rpx;
  align-items: center;
}

.detail-label {
  font-weight: bold;
  color: #303133;
  font-size: 28rpx;
  margin-bottom: 10rpx;
}

.detail-info-card {
  background: #f8f9fa;
  padding: 20rpx;
  border-radius: 8rpx;
}

.info-row {
  display: flex;
  align-items: center;
  gap: 12rpx;
  margin-bottom: 15rpx;
  font-size: 26rpx;
}

.feedback-content {
  background: #f8f9fa;
  padding: 20rpx;
  border-radius: 8rpx;
  line-height: 1.6;
  font-size: 26rpx;
}

.images-grid {
  display: flex;
  gap: 20rpx;
  flex-wrap: wrap;
}

.detail-image {
  width: 150rpx;
  height: 150rpx;
  border-radius: 8rpx;
  cursor: pointer;
}

.admin-reply-content {
  background: #f0f9ff;
  padding: 20rpx;
  border-radius: 8rpx;
  border-left: 4rpx solid #409EFF;
}

.reply-time {
  display: block;
  margin-top: 10rpx;
  font-size: 22rpx;
  color: #909399;
}
</style>
